package yf.mall.component.app;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import yf.mall.entity.*;
import yf.mall.enums.app.AppCourseHotEnum;
import yf.mall.enums.app.AppCoursePurchaseActiveStatusEnum;
import yf.mall.service.UserService;
import yf.mall.service.app.AppCourseItemService;
import yf.mall.service.app.AppCoursePurchaseService;
import yf.mall.service.app.AppCourseService;
import yf.mall.utils.MapperUtils;
import yf.mall.vo.app.common.ListResult;
import yf.mall.vo.app.course.AppCusCourseItemVo;
import yf.mall.vo.app.course.AppCourseVo;
import yf.mall.vo.app.request.CourseListRequest;

import javax.annotation.Resource;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;


@Slf4j
@Component
public class AppCourseComponent {

    private static final String DEFAULT_USER_NAME = "";
    private static final String DEFAULT_USER_AVATAR = "";
    @Resource
    private AppCourseService appCourseService;

    @Resource
    private AppCourseItemService appCourseItemService;

    @Resource
    private UserService userService;

    @Resource
    private QiniuFileComponent qiniuFileComponent;

    @Resource
    private AppCoursePurchaseService appCoursePurchaseService;

    public AppCourseVo getDouxinCourseVo(Long courseId) {
        log.info("查询课程信息，courseId={}", courseId);
        // step1. 通过courseId 查询课程
        AppCourseEntity dxCourse = appCourseService.get(courseId);

        AppCourseVo appCourseVo = convertCourse(dxCourse);
        // step2. 查询课程明细
        AppCourseItemEntity example = new AppCourseItemEntity();
        example.setMainCourseId(courseId);
        List<AppCourseItemEntity> dxCourseItems = appCourseItemService.find(example);

        fillCourseItems(appCourseVo, dxCourseItems);

        return appCourseVo;
    }

    public ListResult<AppCourseVo> getCourseList(Long loginUserId, CourseListRequest request) {
        AppCourseEntityExample query = buildQuery(loginUserId, request);
        PageInfo<AppCourseEntity> page = appCourseService.page(query, new Page<>(request.getPage(), request.getLimit()));
        List<AppCourseEntity> dxCourses = page.getList();
        if (dxCourses.isEmpty()) {
            return new ListResult<>(Collections.emptyList(), false);
        }
        List<AppCourseVo> appCourseVoList = dxCourses.stream().map(dxCourse -> {
            AppCourseVo appCourseVo = convertCourse(dxCourse);
            return appCourseVo;
        }).collect(Collectors.toList());
        return new ListResult<>(appCourseVoList, page.isHasNextPage());
    }


    private AppCourseEntityExample buildQuery(Long loginUserId, CourseListRequest request) {
        AppCourseEntityExample example = new AppCourseEntityExample();
        AppCourseEntityExample.Criteria criteria = example.createCriteria();
        if (request.getType() != null) {
            criteria.andCourseTypeIn(Collections.singletonList(request.getType()));
        }
        if (StringUtils.isNotBlank(request.getKeywords())) {
            criteria.andTitleLike("%" + request.getKeywords() + "%");
        }
        criteria.andLevelIdGreaterThanOrEqualTo(request.getLevelId());


        if(loginUserId != null){
            AppCoursePurchaseEntityExample purchaseExample = new AppCoursePurchaseEntityExample();
            purchaseExample.createCriteria().andUserIdEqualTo(loginUserId).andActiveStatusEqualTo(AppCoursePurchaseActiveStatusEnum.YES.getIndex());
            PageInfo<AppCoursePurchaseEntity> page = appCoursePurchaseService.page(purchaseExample, new Page<>(1, 100));
            if (page.getTotal() > 0) {
                String courseIds = page.getList().stream().map(entity -> entity.getCourseId().toString()).collect(Collectors.joining(","));
                AppCourseEntityExample.Criteria orCriteria = example.createCriteria();
                MapperUtils.addCriterion(orCriteria, "id in (" + courseIds + ")");
            }
        }
        example.setOrderByClause("sort");
        return example;
    }

    public AppCourseVo convertCourse(AppCourseEntity dxCourse) {
        AppCourseVo appCourseVo = new AppCourseVo();
        appCourseVo.setCourseShotCount(dxCourse.getCourseShotCount());
        appCourseVo.setCourseType(dxCourse.getCourseType());
        appCourseVo.setCover(qiniuFileComponent.complementFileUrl(dxCourse.getCover()));
        appCourseVo.setDescription(dxCourse.getDescription());
        appCourseVo.setId(dxCourse.getId());
        appCourseVo.setHot(Objects.equals(AppCourseHotEnum.YES.getIndex(), dxCourse.getHot()));
        appCourseVo.setTitle(dxCourse.getTitle());
        appCourseVo.setTotalTimes(dxCourse.getTotalTimes());
        appCourseVo.setItems(null);
        appCourseVo.setTotalWatchTimes(0L);
        appCourseVo.setLevelId(dxCourse.getLevelId());
        return appCourseVo;
    }

    private void fillCourseItems(AppCourseVo appCourseVo, List<AppCourseItemEntity> dxCourseItems) {
        List<AppCusCourseItemVo> dxCourseVos = dxCourseItems.stream().map(item -> convert(item)).sorted(Comparator.comparing(c -> c.getCourseNo())).collect(Collectors.toList());
        // 填充发布人信息
        fillPublisherToList(dxCourseVos, dxCourseItems);
        appCourseVo.setItems(dxCourseVos);
    }

    private AppCusCourseItemVo convert(AppCourseItemEntity dxCourseItem) {
        AppCusCourseItemVo appCusCourseItemVo = new AppCusCourseItemVo();
        appCusCourseItemVo.setCourseNo(dxCourseItem.getCourseNo());
        appCusCourseItemVo.setCourseNoStr(dxCourseItem.getCourseNoStr());
        appCusCourseItemVo.setCover(qiniuFileComponent.complementFileUrl(dxCourseItem.getCover()));
        appCusCourseItemVo.setDescription(dxCourseItem.getDescription());
        appCusCourseItemVo.setId(dxCourseItem.getId());
        appCusCourseItemVo.setTitle(dxCourseItem.getTitle());
        appCusCourseItemVo.setPublisherId(dxCourseItem.getPublisherId().toString());
        appCusCourseItemVo.setUrl(qiniuFileComponent.complementFileUrl(dxCourseItem.getUrl()));
        // TODO 观看数据单独获取
        appCusCourseItemVo.setWatchTimes(0);
        appCusCourseItemVo.setWatchViewers(0);
        appCusCourseItemVo.setTimes(dxCourseItem.getTime());
        return appCusCourseItemVo;
    }


    private void fillPublisherToList(List<AppCusCourseItemVo> dxCourseVos, List<AppCourseItemEntity> dxCourseItems) {
        Set<Long> publisherIds = dxCourseItems.stream().map(AppCourseItemEntity::getPublisherId).collect(Collectors.toSet());
        // 调用用户接口查询用户信息
        List<UserEntity> userList = userService.finByUserIds(publisherIds);
        Map<Long, UserEntity> usertMap = userList.stream().collect(Collectors.toMap(UserEntity::getId, Function.identity()));
        dxCourseVos.forEach(item -> {
            Long publisherId = Long.parseLong(item.getPublisherId());
            if (!usertMap.containsKey(publisherId)) {
                item.setPublisher(DEFAULT_USER_NAME);
                item.setPublisherAvatar(DEFAULT_USER_AVATAR);
            }
            UserEntity userEntity = usertMap.get(publisherId);
            item.setPublisher(userEntity.getName());
            item.setPublisherAvatar(userEntity.getAvatar());
        });
    }
}
